package com.fhminyi.GUI;

import com.fhminyi.dao.ProductDao;
import com.fhminyi.model.Product;
import com.fhminyi.model.User;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

public class ProductListFrame extends JFrame {
    private User currentUser; // 添加 currentUser 成员变量

    public ProductListFrame(User currentUser) { // 修改构造函数，添加 currentUser 参数
        this.currentUser = currentUser; // 初始化 currentUser
        setTitle("商品列表");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(0, 3));

        ProductDao productDao = new ProductDao();
        try {
            List<Product> products = productDao.getAllProducts();
            for (Product product : products) {
                JLabel nameLabel = new JLabel(product.getProductName());
                JLabel priceLabel = new JLabel("价格: " + product.getPrice());
                JButton detailButton = new JButton("详情"); // 修改按钮文本为“详情”

                detailButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        new ProductDetailFrame(product, currentUser).setVisible(true); // 传递 currentUser 参数
                    }
                });

                panel.add(nameLabel);
                panel.add(priceLabel);
                panel.add(detailButton);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "获取商品列表失败", "错误", JOptionPane.ERROR_MESSAGE);
        }

        add(panel);
    }
}